package com.zxl.yjb.utils;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.zxl.yjb.bean.AreaBean;

import java.util.ArrayList;
import java.util.List;

public class GetPositionUtil {

    public interface SearchResult {
        void onResult(DistrictResult districtResult);

        void onListResult(List<AreaBean> list);
    }

    public static void getPosition(final Context context, String keyWords, final SearchResult searchResult) {
        if(TextUtils.isEmpty(keyWords))
            keyWords = "中华人民共和国";
        DistrictSearch search = new DistrictSearch(context);
        DistrictSearchQuery query = new DistrictSearchQuery();
        query.setKeywords(keyWords);//传入关键字
        query.setShowBoundary(true);//是否返回边界值
        search.setQuery(query);
        search.setOnDistrictSearchListener(new DistrictSearch.OnDistrictSearchListener() {
            @Override
            public void onDistrictSearched(final DistrictResult districtResult) {
                if (searchResult != null) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                searchResult.onResult(districtResult);
                                List<AreaBean> list = new ArrayList<>();
                                for (DistrictItem districtItem : districtResult.getDistrict().get(0).getSubDistrict()) {
                                    list.add(new AreaBean(districtItem.getName(), districtItem.getAdcode()));
                                }
                                searchResult.onListResult(list);
                            }
                        });
                    }

                }
            }
        });//绑定监听器
        search.searchDistrictAnsy();//开始搜索
    }


}
